from flask import Blueprint, request, jsonify
from werkzeug.security import check_password_hash
from api.services.data_service import DataService

bp = Blueprint('auth', __name__)


@bp.route('/login', methods=['POST'])
def login():
    if not request.is_json:
        return jsonify({"error": "请求必须是JSON"}), 400
    
    try:
        data = request.get_json()  # 更安全的获取JSON方式
    except:
        return jsonify({"error": "JSON格式无效"}), 400
    
    username = data.get('username')
    password = data.get('password')
    if not username:
        return jsonify({"error": "需要username"}), 400
    if not password:
        return jsonify({"error": "需要password"}), 400
    
    return jsonify({
            "code": 200,
            "message": "success",
        })
    
    # user = USERS.get(username)
    # if not user or not check_password_hash(user['password'], password):
    #     return jsonify({"error": "用户名或密码错误"}), 401

    # 2. 调用服务层处理数据
    # 简单处理可以直接调用单个方法
    user_data = DataService.login(username,password)
    if user_data is None:
        return jsonify({
            "code": 400,
            "message": "用户名错误",
        })
    
    if user_data['pwd'] != password:
        return jsonify({
            "code": 400,
            "message": "密码错误",
        })
    user_data.pop('pwd', None) # 删除密码字段，如果不存在则返回None不报错
    return jsonify({
            "code": 200,
            "message": "success",
            "data": user_data
        })